<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/18
 * Time: 13:24
 */

namespace Customer\Controllers;


use Admin\Models\crm\XhcustAuth;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\overt\XhovertAreainfo;
use Admin\Models\sys\XhsysEnum;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;

class FollowController extends ControllerBase
{
//    public function indexAction(){
//        echo 'follow';
//    }

    public static $enums = [
        'type' => [ 1=> '学校', 2 =>'人员' ],
    ];


    /**
     * 标签页
     *
     * create by dale 20180420
     */
    public function followTabAction(){
        $this->view->pick('follow/followTab');
    }


    public function extraPower($tag){
        if(User::isAdmin()){
            return true;
        }
        $deps = User::getExtraPower('dep',$tag);
        $userIds = Hrm::getUserByDepId($deps);
        $newArr = [];
        foreach ($userIds as $ids){
            $newArr =array_merge($newArr,$ids);
        }
        $newArr = array_values(array_filter($newArr));

        return $newArr;
    }




    /**
     * follow跟进列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale 20180418
     */
    public function followListAction($type){
        if(!$type){
            return $this->sendViewError('缺少参数');
        }
        Assets::easyUI();
        Assets::importJs('follow/followList.js');
        $this->view->pick('follow/followList');
        Template::exists('followList', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if ($type == 1 ) {  //客户分类
            $enums['province'] = array_column(array_values($this->getAreaByLevel(1)),'areaName','areaCode');
            $enums['province'][''] = '--请选择省--';
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_province', 'data' => $enums['province'], 'default' => '');
            $enums['city'][''] = '--请选择市--';
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_city', 'data' => $enums['city'], 'default' => '');
            $enums['county'][''] = '--请选择县--';
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_county', 'data' => $enums['county'], 'default' => '');

            $enums['iGroupId']= XhsysEnum::getEnumByNodeName('客户组别');
            $enums['iGroupId'][''] = '--组别--';
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_group', 'data' => $enums['iGroupId'], 'default' => '');
        } else if ( $type == 2 ) {
            $enums = [];
            $enums['group'] = $this->getSCBLevelAction();
            $enums['group'][0] = '--市场分组--';
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_group', 'data' => $enums['group'], 'default' => 0);
            $enums['innerGroup'][0] = '--分组地区--';
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_innerGroup', 'data' => $enums['innerGroup'], 'default' => 0);
        }

        $listSearchArr[] = array('type' => 'text', 'class'  =>'easyui-datebox', 'id' => 'List_Search_StartTime', 'label' => ' 时间段：','style'=>'width:100px;');
        $listSearchArr[] = array('type' => 'text', 'class' =>'easyui-datebox', 'id' => 'List_Search_EndTime', 'label' => ' ~ ','style'=>'width:100px;');
        $listSearchArr[] = array('type' => 'text',  'id' => 'list_search', 'label' => '  ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');

        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_see', 'text' => '查看', 'icon' => 'fa-eye');

        $webArr = $tabConfig = [];
        $tabConfig['searchToolbar'] = Template::createSearchToolBar($listSearchArr, !!$listButtonArr);
        $tabConfig['buttonToolbar'] = Template::createButtonToolBar($listButtonArr);
        if($type == 1){
            $tabConfig['tableAttr']['title'] = '跟进情况统计（学校）';
            $tabConfig['field'] = ['cuId', 'schoolName' , 'sProvinceName' , 'sCityName' , 'sCountyName' , 'iGroupId' , 'num'];
            //一个月
            $webArr['startTime'] = date('Y-m-d', mktime(0, 0 , 0,date("m"),1,date("Y")));
            $webArr['endTime']   = date('Y-m-d',mktime(0, 0 , 0,(date("m")+1)%12,1,date("Y"))-24*3600);
        }else if($type == 2) {
            $tabConfig['tableAttr']['title'] = '跟进情况统计（人员）';
            $tabConfig['field'] = ['userId','userName','num'];
            //一周
            $webArr['startTime'] = date('Y-m-d', mktime(0,0,0,date('m'),date('d')-date('w')+1,date('Y')));
            $webArr['endTime']   = date('Y-m-d', mktime(0,0,0,date('m'),date('d')-date('w')+7,date('Y')));
        }else {
            return $this->sendViewError('type类型错误');
        }

        $webArr['List'] = Template::createList('list', 'followList',$tabConfig);


        return $this->view->setVars($webArr);
    }



    /**
     * 获取follow数据
     *
     * create by dale 20180418
     */
    public function getFollowAction(){

        $type  = $this->request->getPost('type','int');
        $key   = $this->request->getPost('key','string');
        $startTime = $this->request->getPost('startTime','string');
        $endTime   = $this->request->getPost('endTime','string');
        $province = $this->request->getPost('province','string');
        $city     = $this->request->getPost('city','string');
        $county   = $this->request->getPost('county','string');
        $group    = $this->request->getPost('group', 'string');
        $innerGroup = $this->request->getPost('innerGroup', 'string');
        $sort       = $this->request->getPost('sort' , 'string' );
        $order      = $this->request->getPost('order' , 'string' );
        try{

            if (!$type) {
                return $this->sendDataGridError('缺少参数');
            }

            $sql = "SELECT t.*,i.iSchoolId,i.sSchoolName,i.iGroupId,i.sProvinceName,i.sCityName,i.sCountyName,i.iCreateUserId as creatorId FROM  XHCust_Track AS t  LEFT JOIN XHCust_Info as i ON i.iCUId = t.iCUId ";

            $conditions   = [];
            $conditions[] = " t.bDelete = 0 ";
            if ($startTime && $endTime) {
                $conditions[] = " DATE_FORMAT(t.tTrackTime,'%Y-%m-%d') <= '{$endTime}' AND  DATE_FORMAT(t.tTrackTime,'%Y-%m-%d') >= '{$startTime}'  ";
            }
            $sql .= " WHERE ".implode(' AND ',$conditions);

            if ($type == 1) {
                $sql = " SELECT count(d.iCUTId) as num ,d.iCUId as iCUId from ({$sql}) as d  GROUP BY d.iCUId  ";
                $sql = " SELECT  IFNULL(k.num , 0) as num , c.iCUId as cuId , c.sSchoolName as schoolName,c.iGroupId,c.sProvinceName,c.sCityName,c.sCountyName,c.iCreateUserId as creatorId  FROM  XHCust_Info as c LEFT JOIN  ({$sql}) as k  ON  c.iCUId = k.iCUId ";
                $conditionArr = [];
                $conditionArr[] = " c.bDelete = 0 ";
                if ($key ) {
                    $conditionArr[] = "  c.sSchoolName like '%{$key}%'  ";
                }

                if ($province && $province != '--请选择省--') {
                    $conditionArr[] = "  c.sProvinceName = '{$province}'  ";
                }

                if ($city && $city != '--请选择市--') {
                    $conditionArr[] = "  c.sCityName = '{$city}'  ";
                }

                if ($county && $county != '--请选择县--') {
                    $conditionArr[] = "  c.sCountyName = '{$county}'  ";
                }

                if ($group ) {
                    $conditionArr[] = "  c.iGroupId = {$group}  ";
                }

                if(!User::isAdmin()){  //和客户管理一样的额外权限
                    $strArr = [];
                    $iAuthId = Main::getLoginUserInfo('userId');
                    $auth = XhcustAuth::find([
                        'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                        'bind' => array('iAuthId' => $iAuthId)
                    ])->toArray();
                    if (count($auth) > 0) {
                        $strArr[] = "  c.iCUId in (" . implode(',' , array_column($auth , 'iCUId')) . ") ";
                    }
                    $strArr[] = "  c.iCreateUserId  = {$iAuthId} ";
                    if(User::getExtraPower('dep','customer',null,true)){ //有扩展权限
                        $userIds = $this->extraPower('customer');
                        if (!is_bool($userIds)){
                            $strArr[] = "  c.iCreateUserId in (" . implode(',' , $userIds) . ") ";
                        }
                    }
                    $conditionArr[] = " ( " . implode(' OR ' , $strArr ) . " )";
                }

                if (count($conditionArr) > 0) {
                    $sql .= " WHERE " . implode(' AND ' , $conditionArr );
                }

                $sql .= " GROUP BY c.iCUId ";
                if ( $order && $sort) {
                    $orderStr = "order by  td.{$sort}  $order ";
                }else{
                    $orderStr = '';
                }

                $data =  Main::runSqlPage(['query' => "select :columns: from ({$sql}) as td   {$orderStr}  ", 'columns' => 'td.*' ] , [ 'iGroupId' => XhsysEnum::getEnumByNodeName('客户组别') ]);

            } else if($type == 2) {
                $depId = XhhrmDepart::findFirst([
                    'columns'    => 'iDepId',
                    'conditions'  => 'bDelete = 0 and sTag =:sTag: ',
                    'bind'       => [ 'sTag' => 'XHSCB' ]
                ]);
                if (!$depId) {
                    return $this->sendDataGridError('未找到市场部');
                }
                $sql = " SELECT count(d.iCUTId) as num ,d.iCreateUserId as userId from ({$sql}) as d  GROUP BY d.iCreateUserId  ";
                $sql = " SELECT  IFNULL(k.num , 0) as num , s.iUserId as userId, s.sStaffName as userName , s.sDepIds FROM   XHHrm_Staff as s  LEFT JOIN ({$sql}) as k  ON s.iUserId = k.userId  ";
                $conditionArr = [];
                $conditionArr[] = "  CONCAT( ',' , s.sDepIds , ',' ) like '%,{$depId->iDepId},%' " ;
                $conditionArr[] = " s.bDelete = 0 ";
                if ($key ) {
                    $conditionArr[] = "  s.sStaffName like '%{$key}%'  ";
                }
                if ( $group && !$innerGroup ) {
                    $conditionArr[] = "    CONCAT( ',' , s.sDepIds , ',' ) like '%,{$group},%' ";
                }else if ( $innerGroup ) {
                    $conditionArr[] = "   CONCAT( ',' , s.sDepIds , ',' ) like '%,{$innerGroup},%' ";
                }

                if(!User::isAdmin()){  //和客户管理一样的额外权限
                    $strArr = [];
                    $iAuthId = Main::getLoginUserInfo('userId');
                    $strArr[] = " s.iUserId  = {$iAuthId} ";
                    if(User::getExtraPower('dep','customer',null,true)){ //有扩展权限
                        $userIds = $this->extraPower('customer');
                        if (!is_bool($userIds)){
                            $strArr[] = "  s.iUserId in (" . implode(',' , $userIds) . ") ";
                        }
                    }
                    $conditionArr[] = " ( " . implode(' OR ' , $strArr ) . " )";
                }

                if (count($conditionArr) > 0) {
                    $sql .= " WHERE " . implode(' AND ' , $conditionArr );
                }

                if ( $order && $sort) {
                    $orderStr = "order by  td.{$sort}  $order ";
                }else{
                    $orderStr = '';
                }

                $data =  Main::runSqlPage(['query' => "select :columns: from ({$sql}) as td  {$orderStr}  ", 'columns' => 'td.*']);
            } else {
                return $this->sendDataGridError('type类型错误');
            }
            return $this->sendJsonResponse($data);
        }catch (\Exception $e){
            return $this->sendDataGridError($e->getMessage());
        }

    }


    /**
     * 获取地区等级
     *
     * @param $level
     * @return array
     *
     * create by dale 20180402
     */
    public function getAreaByLevel($level){
        $area = XhovertAreainfo::find([
            'conditions' => ' areaLevel = :level:',
            'bind'       => ['level'=> $level ]
        ])->toArray();
        $area = array_column($area,null,'areaCode');
        return $area;
    }


    /**
     * 获取市场部分组地区
     *
     * @param null $id
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180427
     */
    public function getSCBLevelAction($id = null){
        if ( !$id ) {
            $arr = Hrm::getDepArray('XHSCB',1);
            $arr = array_column($arr, 'text','id');
            $arr[0] = '--市场分组--';
            $arr = array_reverse($arr,true);
            return $arr;
        } else {
            $arr = XhhrmDepart::getDeps($id);
            $arr[0] = '--分组地区--';
            $arr = array_reverse($arr, true);

            $newArr = [];
            foreach ($arr as $index => $row ) {
                $newArr[] = ['id' => $index , 'text' => $row];
            }
            return $this->sendJsonResponse($newArr);
        }

    }


    /**
     * 跟进详情
     *
     * created by dale 2017/8/9
     */
    public function followDetailAction()
    {
        $this->view->pick('customer/followDetail');
        Assets::importJs('follow/followDetail.js');
        Assets::easyUI();
        Template::exists('followDetail', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        $this->view->setVars(array(
            'List' => Template::createList('List', 'followDetail', [
                'checkbox' => false,
            ]),

        ));
    }

    /**
     * 获取跟进详情数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180420
     */
    public function getFollowDetailAction(){

        $cuId  = $this->request->getPost('cuId', 'int');
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime   = $this->request->getPost('endTime', 'string');
        $userId    = $this->request->getPost('userId','int');
        try{
            $builder = $this->modelsManager->createBuilder()
                ->columns('t.iCUTId,t.tTrackTime,t.iCreateUserId,t.iCUId,t.sStatus,t.tLastModifyDate,t.iLastModifyUserId,p.sSchoolName,u.sUserName,p.iSchoolId')
                ->addFrom('Admin\Models\crm\XhcustTrack', 't')
                ->leftJoin('Admin\Models\crm\XhcustInfo', 't.iCUId=p.iCUId', 'p')
                ->leftJoin('Admin\Models\user\XhsysUser', 't.iCreateUserId=u.iUserId', 'u')
                ->where('t.bDelete=0 AND t.iTrackType=1')
                ->orderBy('t.iCreateUserId,t.tTrackTime DESC');

            if ($startTime && $endTime) {
                $builder->andWhere("t.tTrackTime >=:startTime:", array('startTime' => $startTime))
                    ->andWhere('t.tTrackTime <=:endTime:', array('endTime' => $endTime));
            }

            if ($userId) {
                $builder->andWhere('t.iCreateUserId = :userId:',['userId'=>$userId]);
            }

            if ($cuId) {
                $builder->andWhere('t.iCUId = :cuId:',['cuId' => $cuId ]);
            }

            $data = Main::runBuilderPaginator($builder, true);
            foreach ($data['rows'] as $key => $row) {
                $row['tTrackTime'] = date('Y-m-d', strtotime($row['tTrackTime']));
                $data['rows'][$key] = $row;
            }

            Main::runUserNameById($data['rows'], 'iLastModifyUserId', true);
            return $this->sendJsonResponse($data);

        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 跟进统计
     *
     * create by dale 20180420
     */
    public function indexAction(){
        $this->view->pick('follow/index');
        Assets::importJs('follow/index.js');
        $startTime = date('Y-m-d',mktime(0, 0, 0, 1, 1, date('Y')));
        $endTime = date('Y-m-d',time());
        $this->view->setVars([
            'startTime' => $startTime,
            'endTime'   => $endTime
        ]);
    }

    /**
     * 获取跟踪折线图
     *
     * create by dale 20180419
     */
    public function followLineAction(){
        $this->view->pick('follow/followLine');
        Assets::xhChart();
        Assets::importJs('follow/followLine.js');
    }

    /**
     * 获取跟踪时间线
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180420
     */
    public function getFollowLineAction(){
        $startTime = $this->request->getPost('startTime','string','2017-01-01');
        $endTime   = $this->request->getPost('endTime','string','2018-04-28');
        $dayType   = $this->request->getPost('dayType','string','week');
        if ( !$startTime || !$endTime || !$dayType ) {
            return $this->sendErrorResponse(400,'缺少参数');
        }
        try{
            $sql   = "select COUNT(*) as total from XHCust_Info  WHERE  DATE_FORMAT(tCreateDate,'%Y-%m-%d') <= '{$startTime}' AND IFNULL(iType , 0 ) != 3 AND bDelete = 0 ";
            $total = Tool::getValue($this->db->fetchOne($sql),'total',0); //获取开始时间点之前的客户
            $sql   = "select COUNT(*) as addNum,DATE_FORMAT(tCreateDate,'%Y-%m-%d') as tTime from XHCust_Info  WHERE  DATE_FORMAT(tCreateDate,'%Y-%m-%d') >= '{$startTime}' AND DATE_FORMAT(tCreateDate,'%Y-%m-%d') <= '{$endTime}' AND IFNULL(iType , 0 ) != 3 AND bDelete = 0  GROUP BY DATE_FORMAT(tCreateDate,'%Y-%m-%d') ";

            $addNum = array_column($this->db->fetchAll($sql),'addNum','tTime');

//            $sql = "select COUNT(*) as delNum,DATE_FORMAT(tLastModifyDate,'%Y-%m-%d') as tTime from XHCust_Info  WHERE  DATE_FORMAT(tLastModifyDate,'%Y-%m-%d') >= '{$startTime}' AND DATE_FORMAT(tLastModifyDate,'%Y-%m-%d') <= '{$endTime}' AND iType = 3 AND bDelete = 0 GROUP BY DATE_FORMAT(tLastModifyDate,'%Y-%m-%d') ";
//            $delNum = array_column($this->db->fetchAll($sql),'delNum','tTime');
            $series = [ 0 => [ 'name'=> '客户数目', 'source' => 'customerArr' ] , 1 => [ 'name'=> '跟进数目', 'source' => 'followArr'] ];

            $xList = $this->getXList($dayType,$startTime,$endTime); //获取x轴

            $sql   = "select COUNT(*) as addNum,DATE_FORMAT(tTrackTime,'%Y-%m-%d') as tTime from XHCust_Track  WHERE  DATE_FORMAT(tTrackTime,'%Y-%m-%d') >= '{$startTime}' AND DATE_FORMAT(tTrackTime,'%Y-%m-%d') <= '{$endTime}' AND iTrackType = 1 AND bDelete = 0 GROUP BY DATE_FORMAT(tTrackTime,'%Y-%m-%d') ";

            $followNum = array_column($this->db->fetchAll($sql),'addNum','tTime');

            $customerArr = $this->getCustomerArr($dayType,$xList,$total,$addNum);
            $followArr = $this->getFollowArr($dayType,$xList,$followNum);
            if($dayType != 'day'){  //如果是不是按日计算
                $xList = array_keys($xList);
            }
            return $this->sendJsonResponse(['series'=>$series,'xList'=>$xList,'customerArr'=>$customerArr,'followArr'=>$followArr]);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }


    }

    /**
     * 获取x轴坐标 时间段
     *
     * @param $type
     * @param $startTime
     * @param $endTime
     * @return array   ['年'=>'开始时间~结束时间']
     * @throws \Exception
     *
     * create by dale 20180420
     */
    public function getXList($type,$startTime,$endTime){
        try{
            $xList = [];
            if($type == 'day'){ //天
                for($i =strtotime($startTime) ; $i<= strtotime($endTime); $i+= 24*3600 ){
                    $xList[] = date('Y-m-d',$i);
                }
                return $xList;
            }
            if($type == 'week'){ //周
                $startDate = strtotime($startTime);
                $endDate   = strtotime($endTime);
                if (date("w",$startDate) != 1) {  //如果不为周一则取下周
                    $xList[date('Y',$startDate).'年第'.intval(date('W',$startDate)).'周'] = $startTime.'~'.date('Y-m-d',strtotime("this week sunday", $startDate));
                    $startDate = strtotime("next monday", $startDate);
                }
                $countWeek = ($endDate-$startDate)/(7*24*3600);
                for($i = 0 ; $i< $countWeek ; $i++ ){
                    $startDay = date('Y-m-d',$startDate);
                    $endDay = date('Y-m-d', strtotime("+ 6 days",$startDate));
                    if($endDay < $endTime){
                        $xList[date('Y',$startDate).'年第'.intval(date('W',$startDate)).'周'] = $startDay.'~'.$endDay;
                        $startDate = strtotime("+ 1 day",strtotime($endDay));
                    }else{
                        $xList[date('Y',$startDate).'年第'.intval(date('W',$startDate)).'周'] = $startDay.'~'.$endTime;
                    }
                }
//                var_dump($xList);die;
                return $xList;
            }
            if ($type == 'month') { //月份
                $startDate = strtotime($startTime);
                $endDate   = strtotime($endTime);
                $monthCount = (intval(date('Y',$endDate)) - intval(date('Y',$startDate))) * 12 + (intval(date('m',$endDate))  - intval(date('m',$startDate)))+1;

                for ($i = 0 ; $i< $monthCount ; $i++ ) {
                    $startDay = date('Y-m-d',$startDate);
                    if (date('m',$startDate) == 12 ) {
                        $endDay = date('Y-m-d', mktime(0, 0, 0, 12 , 31,date('Y',$startDate)));
                    }else{
                        $endDay = date('Y-m-d', mktime(0, 0, 0, date('m',$startDate)+1 , 1,date('Y',$startDate)) - 24*3600);
                    }

                    if($endDay < $endTime){
                        $xList[date('Y',$startDate).'年第'.intval(date('m',$startDate)).'月'] = $startDay.'~'.$endDay;
                        $startDate = strtotime("+ 1 day",strtotime($endDay));
                    }else{
                        $xList[date('Y',$startDate).'年第'.intval(date('m',$startDate)).'月'] = $startDay.'~'.$endTime;
                    }
                }
                return $xList;
            }
            if($type == 'quarter') { //季度
                $startDate = strtotime($startTime);
                $endDate   = strtotime($endTime);
                $seasonCount = (intval(date('Y',$endDate)) - intval(date('Y',$startDate))) * 4 + ( ceil((date('n',$endDate))/3) - ceil((date('n',$startDate))/3) ) + 1 ;
                var_dump($seasonCount);
                for($i = 0 ; $i< $seasonCount ; $i++ ){
                    $startDay = date('Y-m-d',$startDate);
                    $nowSeason = ceil((date('n',$startDate))/3);
                    $endDay   = date('Y-m-d', mktime(0,0,0,$nowSeason*3,date('t',mktime(0, 0 , 0,$nowSeason*3,1,date("Y"))),date('Y',$startDate)));
                    if(strtotime($endDay) < strtotime($endTime)){
                        $xList[date('Y',$startDate).'年第'.$nowSeason.'季'] = $startDay.'~'.$endDay;
                        $startDate = strtotime("+ 1 day",strtotime($endDay));
                    }else{
                        $xList[date('Y',$startDate).'年第'.$nowSeason.'季'] = $startDay.'~'.$endTime;
                    }
                }
                return $xList;
            }
            if ($type == 'year') {
                $startDate = strtotime($startTime);
                $endDate   = strtotime($endTime);
                $yearCount = intval(date('Y',$endDate)) - intval(date('Y',$startDate)) + 1;
                for ($i = 0 ; $i < $yearCount ; $i++) {
                    $startDay = date('Y-m-d',$startDate);
                    $endDay   = date('Y-m-d',mktime(0, 0, 0, 12, 31, date('Y',$startDate)));
                    if(strtotime($endDay) < strtotime($endTime)){
                        $xList[date('Y',$startDate).'年'] = $startDay.'~'.$endDay;
                        $startDate = strtotime("+ 1 day",strtotime($endDay));
                    }else{
                        $xList[date('Y',$startDate).'年'] = $startDay.'~'.$endTime;
                    }
                }
                return $xList;
            }
            throw new \Exception('类型不匹配');
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 处理客户数据
     *
     * @param $type
     * @param $xList
     * @param $total
     * @param $addNum
     * @param $delNum
     * @return array
     * @throws \Exception
     *
     * create by dale 20180420
     */
    public function getCustomerArr($type,$xList,$total,$addNum){

        $customerArr = [];
        if($type == 'day'){  //一天天加
            foreach ($xList as $index => $row){
                $num = Tool::getValue($addNum,$row,0);
                $total += $num;
                $customerArr[] = $total;
            }
            return $customerArr;
        }else if ($type == 'week' || $type == 'month' || $type = 'quarter' || $type = 'year' ){
            foreach ($xList as $index => $row) {
                $dayArr   = explode('~',$row);
                $startDay = $dayArr[0];
                $endDay   = $dayArr[1];
                $num = 0;
                for ($i = strtotime($startDay) ; $i <= strtotime($endDay) ; $i+=24*3600 ) { //计算一周,一个月的数量
                    $num = Tool::getValue($addNum,date('Y-m-d',$i),0);
                    $total += $num;
                }
                $customerArr[] = $total;
            }
            return $customerArr;
        }else{
            throw new \Exception('类型不匹配');
        }


    }

    /**
     *  处理客户跟踪
     *
     * @param $type
     * @param $xList
     * @param $followNum
     * @return array
     * @throws \Exception
     *
     * create by dale 20180420
     */
    public function getFollowArr($type,$xList,$followNum){
        if ($type =='day') {
            $followArr = [];
            foreach ($xList as $index => $row) {
                $followArr[] = intval(Tool::getValue($followNum,$row,0));
            }
            return $followArr;
        }else if ($type =='week' || $type == 'month' || $type = 'quarter' || $type = 'year' ) {
            $followArr = [];
            foreach ($xList as $index => $row) {
                $dayArr   = explode('~',$row);
                $startDay = $dayArr[0];
                $endDay   = $dayArr[1];
                $total = 0;
                for ($i = strtotime($startDay); $i <= strtotime($endDay);$i+= 24*3600 ) {
                    $total += intval(Tool::getValue($followNum,date('Y-m-d',$i),0));
                }
                $followArr[] = $total; //获取一周的数据
            }
            return $followArr;
        }else{
            throw new \Exception('类型不匹配');
        }

    }
}